package com.crm.controller.purchase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.exception.ServiceException;
import com.crm.pojo.*;
import com.crm.service.client.ClientInfoService;
import com.crm.service.client.ContactService;
import com.crm.service.client.impl.ClientInfoServiceImpl;
import com.crm.service.client.impl.ContactServiceImpl;
import com.crm.service.permission.UserInfoService;
import com.crm.service.purchaseService.PurchaseService;
import com.crm.service.purchaseService.PurproductDetailsService;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ProPurchaseController {
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private PurproductDetailsService purproductDetailsService;
    @Autowired
    private ContactServiceImpl contactService;
    @Autowired
    private ClientInfoServiceImpl clientInfoService;
    @Autowired
    private UserInfoService userInfoService;

    //打开采购管理选项卡
    @GetMapping("pPurchaseM")
    public String toPurchase(){
        return "purchase/proPurchase";
    }
    @GetMapping("to-form-pro-highLevel-dy")
    public String toFormProhighleveldy(){
        return "product/formProhldy";
    }

    //分页查询所有采购单
    @PostMapping("allPurPaged")
    @ResponseBody
    public Map allProPaged(int page, int rows) {
        Long total = purchaseService.queryCount();
        List<Purchase> pro = purchaseService.allPurchasesPaged(page, rows);
        HashMap map = new HashMap<>();
        map.put("total", total);
        map.put("rows", pro);
        return map;
    }
    //模糊查询（根据经手人名称或者采购主题）
    @PostMapping("getAllPurchasesBymh")
    @ResponseBody
    public List<Purchase> getAllPurchasesBymh(String q){
        return purchaseService.getAllPurchasesBymh(q);
    }

    //批量删除采购单（逻辑删除）而且会删除采购单下的采购商品明细
    @PostMapping("pro-purchases-del")
    @ResponseBody
    public Result proCategoriesDel(String rowsId){
        String[] idsS = rowsId.split(",");
        Long[] ids=new Long[idsS.length];
        for(int i =0;i<idsS.length;i++){
            ids[i] = Long.parseLong(idsS[i]);
        }
        try{
            for(int i = 0; i < ids.length;i++){
                Purchase purchase =purchaseService.findOneById(ids[i]);
                purchase.setPurchaseIsDel("是");
                purchaseService.savePurchase(purchase);
                purproductDetailsService.deleteAllBypurId(ids[i]);
            }
            return Result.SUCCESS;
        }catch (ServiceException e){
            e.printStackTrace();
            return new Result("删除失败！");
        }
    }
    //打开新建采购单表单
    @GetMapping("to-form-pur-add")
    public String toFormPurAdd(){
        return "purchase/newPurchase";
    }
    //模糊查询所有采购商根据采购商的名称
    @PostMapping("getAllClientBymh")
    @ResponseBody
    public List<ClientInfo> findAllClientByMh(String q){
        return clientInfoService.findAllClientByMh(q);
    }
    //模糊查询所有当前采购商下的联系人(根据联系人名称)
    @PostMapping("getAllContactBymh")
    @ResponseBody
    public List<Contact> findAllContactByMh(Long cid){
        return contactService.findAllContactByMh(cid);
    }
    //新建采购单 涉及到采购产品明细
    @PostMapping("newPurchase-form-sub")
    @ResponseBody
    public Result newPurchase(Purchase purchase){
        try{
            purchase.setPurchaseIsDel("否");
            purchase.setPurstatus("待采购");
            purchase.setPurmoney(0d);
            purchase.setPurCheck("未审核");
            purchaseService.savePurchase(purchase);
            return Result.SUCCESS;
        }catch(ServiceException e){
            e.printStackTrace();
            return new Result("添加失败！");
        }
    }
    //打开编辑采购明细表单
    @GetMapping("to-form-pur-update")
    public String toFormpurUpdate(){
        return "purchase/updatePurchase";
    }
    //加载编辑数据根据purid
    @GetMapping("getRowData3")
    @ResponseBody
    public Purchase getRowData3(Long purid){
       Purchase purchase = purchaseService.findOneById(purid);
       //经手人真实姓名
       if(purchase.getPurUserId()!=null){
           purchase.setPurUsername(userInfoService.findOne(purchase.getPurUserId()).getUrealName());
       }
       //联系人姓名
       if(purchase.getContactId()!=null){
           purchase.setContactName(contactService.findContactBycontactid(purchase.getContactId()).getContactName());
       }else{
           purchase.setContactName("暂无联系人");
       }
       //采购商名称
        if(purchase.getClientId()!=null){
            purchase.setClientname(clientInfoService.findOne(purchase.getClientId()).getCname());
        }
        return purchase;
    }
    //添加一行商品数据dialog
    @GetMapping("to-addLine-dialog")
    public String toAddLinedialog(){
        return "purchase/addLinePro";
    }
    //修改采购商品明细信息表单
    @GetMapping("to-editLine-dialog")
    public String toeditLinedialog(){
        return "purchase/editAddLinePro";
    }
    //提交采购修改表单
    @PostMapping("editPurchase-form-sub")
    @ResponseBody
    public Result editPurchase(Purchase purchase){
        try{
            purchase.setPurstatus("采购完成-待入库");
            purchase.setPurCheck("未审核");
            purchase.setPurchaseIsDel("否");
            purchase.setPurmoney(purproductDetailsService.findAllByPurid(purchase.getPurid()));
            purchaseService.savePurchase(purchase);
            return Result.SUCCESS;
        }catch(ServiceException e){
            e.printStackTrace();
            return new Result("编辑失败！");
        }
    }
    //发送ajax请求
    @PostMapping("sendData")
    @ResponseBody
    public Result savePurProdetails(String jsonStr,String purid){
        try{
            Long pid = Long.valueOf(purid);
            //清空所有采购单下的采购产品明细
            purproductDetailsService.deleteAllBypurId(pid);
            if(!"[]".equals(jsonStr)){
                List<Purchaseproductiondetail> jsonArray = JSON.parseArray(jsonStr, Purchaseproductiondetail.class);
                //创建所有采购单下的采购产品明细
                for(Purchaseproductiondetail p:jsonArray){
                    purproductDetailsService.addNewdetails(p);
                }
            }
            return Result.SUCCESS;
        }catch (ServiceException e){
            e.printStackTrace();
            return new Result("ajax失败！");
        }
    }
    //在编辑产品明细中查看采购单下的采购产品明细列表
    @PostMapping("allppd")
    @ResponseBody
    public List<Purchaseproductiondetail> allPpd(Long purid){
        return purproductDetailsService.findAllppdByPurid(purid);
    }

    //打开高级查询表单
    @GetMapping("to-form-pur-highLevel")
    public String toFormPurHl(){
        return "purchase/proPurchasehl";
    }

    //高级查询
    @PostMapping("Purchase-form-hlq-sub")
    @ResponseBody
    public Map proFormhlq(Purchase purchase, int page, int rows){
        Map map = new HashMap<>();
        Long count = purchaseService.proHlqCount(purchase);
        List<Purchase> pro = purchaseService.proHlq(purchase,page,rows);
        map.put("total",count);
        map.put("rows",pro);
        return map;
    }
    //打开采购视图表单
    @GetMapping("to-form-pur-details")
    public String toFormPurdetails(){
        return "purchase/viewPurchase";
    }
}
